package com.auto.autoapp.util

import kotlin.math.roundToInt
import kotlin.math.abs
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.Calendar

object StringUtil {
    fun parseCount(text: String?): Int {
        if (text.isNullOrEmpty()) return 0
        val regex = Regex("""\d+(?:\.\d+)?""")
        val match = regex.find(text) ?: return 0
        val base = match.value.toDoubleOrNull() ?: return 0
        val rest = text.substring(match.range.last + 1)
        val hasWan = rest.contains("万")
        return if (hasWan) (base * 10000).roundToInt() else base.toInt()
    }

    /**
     * 从字符串中查找并解析时间，格式为 "yyyy-MM-dd HH:mm"。
     * 若匹配成功，返回对应的毫秒时间戳；否则返回 null。
     */
    fun findDateTimeMillis(text: String?): Long? {
        if (text.isNullOrEmpty()) return null
        val regex = Regex("""\b\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}\b""")
        val match = regex.find(text) ?: return null
        val dateStr = match.value
        return try {
            val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).apply {
                isLenient = false
            }
            sdf.parse(dateStr)?.time
        } catch (_: Exception) {
            null
        }
    }

    /**
     * 与当前时间比较，返回差值（目标时间 - 当前时间）的毫秒数。
     * 若无法从文本中解析到 "yyyy-MM-dd HH:mm"，返回 null。
     */
    fun diffFromNowMillis(text: String?): Long? {
        val target = findDateTimeMillis(text) ?: return null
        return System.currentTimeMillis() - target
    }

    /**
     * 计算两个时间相差的天数（向下取整）。
     * 入参为包含格式 "yyyy-MM-dd HH:mm" 的字符串；任一解析失败时返回 null。
     */
    fun diffDays(text1: String?): Int? {
        val t1 = findDateTimeMillis(text1) ?: return null
        val t2 = System.currentTimeMillis()
        val diffMs = abs(t1 - t2)
        return (diffMs / (24L * 60L * 60L * 1000L)).toInt()
    }

    fun toStandardDateTime(text: String?): String? {
        val s = text?.trim() ?: return null
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())

        if (s == "刚刚") {
            val cal = Calendar.getInstance()
            cal.set(Calendar.SECOND, 0)
            cal.set(Calendar.MILLISECOND, 0)
            return sdf.format(cal.time)
        }

        val minAgo = Regex("""(\d+)\s*分钟(?:前)?""").find(s)?.groupValues?.get(1)?.toIntOrNull()
        if (minAgo != null) {
            val cal = Calendar.getInstance()
            cal.add(Calendar.MINUTE, -minAgo)
            cal.set(Calendar.SECOND, 0)
            cal.set(Calendar.MILLISECOND, 0)
            return sdf.format(cal.time)
        }

        val hourAgo = Regex("""(\d+)\s*小时(?:前)?""").find(s)?.groupValues?.get(1)?.toIntOrNull()
        if (hourAgo != null) {
            val cal = Calendar.getInstance()
            cal.add(Calendar.HOUR_OF_DAY, -hourAgo)
            cal.set(Calendar.SECOND, 0)
            cal.set(Calendar.MILLISECOND, 0)
            return sdf.format(cal.time)
        }

        val fullDateTime = Regex("""^\d{4}-\d{2}-\d{2}(?:\s\d{2}:\d{2})?$""")
        if (fullDateTime.matches(s)) {
            val value = if (s.length == 10) "$s 00:00" else s
            return try {
                val d = sdf.parse(value)
                d?.let { sdf.format(it) }
            } catch (_: Exception) { null }
        }

        val mdWithOptTime = Regex("""^\d{2}-\d{2}(?:\s\d{2}:\d{2})?$""")
        if (mdWithOptTime.matches(s)) {
            val year = Calendar.getInstance().get(Calendar.YEAR)
            val value = if (s.length == 5) "$year-$s 00:00" else "$year-$s"
            return try {
                val d = sdf.parse(value)
                d?.let { sdf.format(it) }
            } catch (_: Exception) { null }
        }

        val timeMatch = Regex("""(\d{2}):(\d{2})""").find(s)
        val hour = timeMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
        val minute = timeMatch?.groupValues?.get(2)?.toIntOrNull() ?: 0

        var dayOffset: Int? = null
        if (s.contains("昨天")) dayOffset = 1
        if (s.contains("前天")) dayOffset = 2
        val daysAgo = Regex("""(\d+)天前""").find(s)?.groupValues?.get(1)?.toIntOrNull()
        if (daysAgo != null) dayOffset = daysAgo

        if (dayOffset != null) {
            val cal = Calendar.getInstance()
            cal.add(Calendar.DAY_OF_YEAR, -dayOffset)
            cal.set(Calendar.HOUR_OF_DAY, hour)
            cal.set(Calendar.MINUTE, minute)
            cal.set(Calendar.SECOND, 0)
            cal.set(Calendar.MILLISECOND, 0)
            return sdf.format(cal.time)
        }

        return null
    }
}
